//
//  Extension.swift
//  Runner
//
//  Created by Lazyloading on 2021/7/8.
//

import Foundation

extension UIViewController {
    static func hx_currentController() -> UIViewController {
        var currentViewController = self.hx_getCurrentRootCOntroller()
        let runLoopFind = true
        while runLoopFind == true {
            if currentViewController.presentedViewController != nil {
                currentViewController = currentViewController.presentedViewController!
            } else if currentViewController.isKind(of: UINavigationController.self) {
                let navi = currentViewController as? UINavigationController
                currentViewController = navi?.children.last! ?? UIViewController()
            } else if currentViewController.isKind(of: UITabBarController.self) {
                let tabbar = currentViewController as? UITabBarController
                currentViewController = tabbar?.selectedViewController! ?? UIViewController()
            } else {
                let childViewControllerCount = currentViewController.children.count
                if childViewControllerCount > 0 {
                    currentViewController = currentViewController.children.last!
                    return currentViewController
                } else {
                    return currentViewController
                }
            }
        }
        return currentViewController
    }
    static func hx_getCurrentRootCOntroller() -> UIViewController {
        var currentWindowVC : UIViewController
        var window = UIApplication.shared.keyWindow
        if window?.windowLevel != .normal {
            let windows = UIApplication.shared.windows
            for tempWindow in windows where tempWindow.windowLevel == .normal {
                window = tempWindow
            }
        }
        let frontView = (window?.subviews.first)! as UIView
        let nextResponder = frontView.next
        if (nextResponder?.isKind(of: UIViewController.self)) == true {
            currentWindowVC = nextResponder as? UIViewController ?? UIViewController()
        } else {
            currentWindowVC = (window?.rootViewController)!
        }
        return currentWindowVC
    }
}
